package protocol;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class CommSckServer implements Runnable {
	private ServerSocket sSckt = null;
	private Socket sckt = null;
	private ObjectInputStream is = null;
	private ObjectOutputStream os = null;
	private CommandRelay cmdRly;
	private Thread thread;
	private int port;
	
	public CommSckServer(int port, CommandRelay cmdRly) {
		this.port = port;
		this.cmdRly = cmdRly;
		thread = new Thread(this);
		thread.start();
	}

	public void run() {
		try {
			sSckt = new ServerSocket(port);
			System.out.println("Server: socket open!");
			
			sckt = sSckt.accept();
			System.out.println("Server: connection accepted!");
			is = new ObjectInputStream(sckt.getInputStream());
			os = new ObjectOutputStream(sckt.getOutputStream());
			while(sckt.isConnected()) {
				try {
					System.out.println("Serv: Available: " +is.available());
					if (is.available() != 0) {
						Cmd cmd = (Cmd)is.readObject();
						cmdRly.addInCmd(/*(Cmd)is.readObject()*/cmd);
						System.out.println("Server Incommand: " + cmd.getCommand() + " "  + cmd.getAgvNummer() + " " + cmd.getKraannr());
					}
					
				} 
				catch (ClassNotFoundException e) {
					e.printStackTrace();
				}  
				Cmd cmd = cmdRly.getOutCmd();
				if (cmd != null) {
					os.writeObject(cmd/*cmdRly.getOutCmd()*/);
					System.out.println("Server Outcommand: " + cmd.getCommand() + " "  + cmd.getAgvNummer() + " " + cmd.getKraannr());
				}			
			}
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
